package net.controller;

import net.common.ServiceResponse;
import net.pojo.Cart;
import net.pojo.Category;
import net.pojo.User;
import net.service.CartService;
import net.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @Author admin
 * @Date 2019/4/18 8:55
 */
@Controller
@RequestMapping("/cart")
public class CartController {
    @Autowired
    CartService cartService;
    @Autowired
    CategoryService categoryService;
    @RequestMapping("/mycart")
    public String mycart(HttpServletRequest request, Model model){
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        List<Cart> clist = cartService.findByUid(user.getId());
        model.addAttribute("clist",clist);
        return "/client/cart.jsp";
    }

    @RequestMapping("/addCart")
    @ResponseBody
    public ServiceResponse addCart(@RequestBody Cart cart, HttpServletRequest request){
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        cart.setUid(user.getId());
        int addCart = cartService.addCart(cart);
        if (addCart > 0){
            return ServiceResponse.createSuccessAndMessage("添加购物车成功");
        }
        return ServiceResponse.createErrorAndMessage("添加购物车失败");
    }
    @RequestMapping("/updateQuantity")
    @ResponseBody
    public ServiceResponse updateQuantity(@RequestBody Cart cart,HttpServletRequest request){
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        cart.setUid(user.getId());
        int serviceResponse = cartService.updateQuantity(cart);
        return ServiceResponse.createSuccessStatus();

    }

    @RequestMapping("/deleteById")
    public String deleteById(String pid){

        int deleteById = cartService.deleteById(pid);
        return "redirect:/cart/mycart.do";
    }

    @RequestMapping("/order")
    public String order(HttpServletRequest request, Model model){
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        List<Cart> clist = cartService.findByUid(user.getId());
        model.addAttribute("user",user);
        model.addAttribute("clist",clist);
        return "/client/order.jsp";
    }

}
